#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
台球厅管理系统后端API服务
基于Flask框架构建RESTful API
"""

from flask import Flask, jsonify, request, session
from flask_cors import CORS
from flask_migrate import Migrate
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime, timedelta
import jwt
import os
from functools import wraps

# 导入数据库配置
from database import db, init_app
from utils.decorators import token_required, admin_required

# 创建Flask应用
app = Flask(__name__)

# 配置
app.config['SECRET_KEY'] = 'billiard-hall-secret-key-2025'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@localhost:3306/billiard_hall'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['JWT_SECRET_KEY'] = 'billiard-jwt-secret'

# 初始化扩展
init_app(app)
migrate = Migrate(app, db)
# 配置CORS解决跨域问题
CORS(app, resources={
    r"/*": {
        "origins": "*",
        "allow_headers": "*",
        "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
    }
}, supports_credentials=True)

# 健康检查
@app.route('/api/health')
def health_check():
    return jsonify({
        'status': 'success',
        'message': '台球厅管理系统API服务正常运行',
        'timestamp': datetime.now().isoformat()
    })

# 错误处理
@app.errorhandler(404)
def not_found_error(error):
    return jsonify({'message': '接口不存在'}), 404

@app.errorhandler(500)
def internal_error(error):
    db.session.rollback()
    return jsonify({'message': '服务器内部错误'}), 500

# 导入模型和路由
from models.user import User
from models.order import Order
from models.recharge import Recharge
from models.table import BilliardTable
from models.admin import Admin
from models.staff import Staff
from models.task import Task

from routes.auth import auth_bp
from routes.user import user_bp
from routes.order import order_bp
from routes.recharge import recharge_bp
from routes.table import table_bp
from routes.admin import admin_bp
from routes.staff import staff_bp
from routes.task import task_bp

# 注册蓝图
app.register_blueprint(auth_bp, url_prefix='/api/auth')
app.register_blueprint(user_bp, url_prefix='/api/users')
app.register_blueprint(order_bp, url_prefix='/api/orders')
app.register_blueprint(recharge_bp, url_prefix='/api/recharges')
app.register_blueprint(table_bp, url_prefix='/api/tables')
app.register_blueprint(admin_bp, url_prefix='/api/admin')
app.register_blueprint(staff_bp, url_prefix='/api/staff')
app.register_blueprint(task_bp, url_prefix='/api/tasks')

if __name__ == '__main__':
    with app.app_context():
        # 创建数据库表
        db.create_all()
        
        # 创建默认管理员账户
        from models.admin import Admin
        if not Admin.query.filter_by(username='admin').first():
            admin = Admin(
                username='admin',
                password='admin123',
                name='系统管理员',
                email='admin@billiard.com'
            )
            db.session.add(admin)
            db.session.commit()
            print("已创建默认管理员账户: admin / admin123")
    
    app.run(debug=True, host='0.0.0.0', port=5000)